import React, { useEffect, useState } from 'react';
import { useParams } from '@umijs/max';
import { Spin, Button, Tag, message, Image } from 'antd';
import { ArrowLeftOutlined, CalendarOutlined, ProfileOutlined, TagOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { MusicInfoDetail, getMusicInfoDetail } from '@/services/MusicInfoService';
import styles from './detail.less';

const MusicDetail: React.FC = () => {
  const params = useParams<{ idBase64: string }>();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<MusicInfoDetail>();
  const [isHorizontal, setIsHorizontal] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      if (!params.idBase64) return;
      try {
        setLoading(true);
        const data = await getMusicInfoDetail(Number(atob(params.idBase64)));
        setData(data);
      } catch (error) {
        message.error('获取音乐详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [params.idBase64]);

  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    console.log(e);
    const img = e.target as HTMLImageElement;
    setIsHorizontal(img.naturalWidth > img.naturalHeight);
  };

  const handleBack = () => {
    history.back();
  };

  const getDefaultCover = (name: string) => {
    const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
    const index = name.length % colors.length;
    return (
      <div className={styles.defaultCover} style={{ backgroundColor: colors[index] }}>
        {name.slice(0, 2)}
      </div>
    );
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <Spin size="large" />
      </div>
    );
  }

  if (!data) {
    return null;
  }

  return (
    <div className={styles.musicDetailContent}>
      <div className={styles.header}>
        <Button
          type="link"
          icon={<ArrowLeftOutlined />}
          onClick={handleBack}
          style={{ marginLeft: '-15px' }}
        >
          返回
        </Button>
      </div>

      <div className={`${styles.mainContent} ${isHorizontal ? styles.horizontal : styles.vertical}`}>

        <div className={styles.coverSection}>
          <div className={styles.coverWrapper}>
            {data.cover?.id ? (
              <Image
                src={`/api/file/play/${data.cover.id}`}
                alt={data.name}
                className={styles.cover}
                onLoad={handleImageLoad}
                preview={{
                  mask: '预览',
                  maskClassName: styles.previewMask
                }}
                fallback="/images/default-cover.png"
              />
            ) : getDefaultCover(data.name)}
          </div>
        </div>

        <div className={styles.infoSection}>
          <h1 className={styles.title}>{data.name}</h1>

          <div className={styles.basicInfo}>
            <div className={styles.infoItem}>
              <ProfileOutlined className={styles.icon} />
              <span className={styles.label}>专辑:</span>
              <span className={styles.value}>{data.album}</span>
            </div>

            <div className={styles.infoItem}>
              <CalendarOutlined className={styles.icon} />
              <span className={styles.label}>发行日期:</span>
              <span className={styles.value}>{data.releaseDate}</span>
            </div>

            {data.genre && (
              <div className={styles.infoItem}>
                <TagOutlined className={styles.icon} />
                <span className={styles.label}>类型:</span>
                <span className={styles.value}>
                  {data.genre.split(/[,，、]/g).map((tag, index) => (
                    <Tag key={index} color="blue">{tag.trim()}</Tag>
                  ))}
                </span>
              </div>
            )}
          </div>

          {data.description && (
            <div className={styles.description}>
              <div className={styles.sectionTitle}>简介</div>
              <div className={styles.content}>{data.description}</div>
            </div>
          )}

          <div className={styles.sourceSection}>
            <div className={styles.sectionTitle}>音源</div>
            {data.musicSourceInfo && data.musicSourceInfo.length > 0 ? (
              <div className={styles.sourceList}>
                {data.musicSourceInfo.map((source, index) => (
                  <div key={index} className={styles.sourceItem}>
                    <span className={styles.sourceName}>{source.sourceName}</span>
                    <a href={source.sourceUrl} target="_blank" rel="noopener noreferrer">
                      <Button type="link">查看</Button>
                    </a>
                  </div>
                ))}
              </div>
            ) : (
              <div className={styles.emptyTip}>暂无音源信息</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default MusicDetail; 